package com.grantz.function.bbs.core.controller;

import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.grantz.function.bbs.core.entity.Group;
import com.grantz.function.bbs.core.inter.GroupService;
import com.grantz.model.bbs.GroupModel;
import com.grantz.model.bbs.GroupSearch;
import com.grantz.models.base.element.page.ElementPage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/v1/groups")
@Api(value="群组",tags={"群组接口"})
public class GroupController {

	@Resource
	private GroupService  groupService;

	// 获取群组用户
	@ApiOperation(value = "获取分页信息")
	@GetMapping
	public ResponseEntity<ElementPage<GroupModel>>  get( GroupSearch query) throws Exception{
		ElementPage<GroupModel> element =  groupService.queryElementPage(query);
		return new ResponseEntity<ElementPage<GroupModel>>(element ,HttpStatus.CREATED);
	}

	@ApiOperation(value = "获取单条群组信息")
	@GetMapping("pk")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id" ,value = "主键",dataType = "string",paramType = "query",example = "tk77889900")
	})
	public ResponseEntity<GroupModel>  pk(String id) throws Exception{
		Optional<Group>  option =  groupService.findOneById(id);
		if(option.isPresent()) {
			Group  group =   option.get();
			return new ResponseEntity<>(groupService.popOne(group),HttpStatus.OK);
		}
		return new ResponseEntity<>(HttpStatus.NOT_FOUND);
	}

	@ApiOperation(value = "保存,群组")
	@PutMapping
	public ResponseEntity<?>  save(@RequestBody GroupModel model){
		groupService.save(pop(new Group() ,model));
		return new ResponseEntity<>(HttpStatus.CREATED);
	}

	@ApiOperation(value = "更新,群组")
	@PostMapping
	public ResponseEntity<?>  update(@RequestBody GroupModel model){
		Optional<Group> option = groupService.findOneById(model.getId());
		if(option.isPresent()) {
			groupService.save(pop(option.get() , model));
		}
		return new ResponseEntity<>(HttpStatus.CREATED);
	}

	private Group pop(Group entity ,GroupModel model) {
		entity.setGroupName(model.getGroupName());
		entity.setGroupDesc(model.getGroupDesc());
		entity.setLongitude(model.getLongitude());
		entity.setLatitude(model.getLatitude());
		entity.setBigType(model.getBigType());
		entity.setMidType(model.getMidType());
		return entity;
	}
}
